package com.easybuilder.common.aspect;

import com.easybuilder.common.config.datasource.DataSourcePool;
import com.easybuilder.common.utils.DBUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.sql.Connection;
import java.sql.SQLException;

@Aspect
@Component
@Slf4j
public class TransactionalAspect {


    //定义切点(带@Transactional注解的方法)
    @Pointcut("@annotation(com.easybuilder.common.annotation.Transactional)")
    public void pointcut() {

    }

    //进入方法前，获取数据库连接，关闭自动事务，并存放至本地线程
    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        Connection conn = DataSourcePool.getConnection();
        try {
            if (conn != null && !conn.isClosed()) {
                conn.setAutoCommit(false);
                //设置事务结束标识为开始
                DBUtil.setTranscationalStart();
                log.info("jdbc关闭自动提交事务");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @After("pointcut()")
    public void after(JoinPoint joinPoint) {
        Connection conn = DataSourcePool.getConnection();
        if (conn != null ) {
            try {
                conn.commit();
                log.info("事务提交");
                //事务结束
                DBUtil.setTranscationalOver();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                //释放资源
                DataSourcePool.returnConnection();
            }
        }
    }

    @AfterThrowing("pointcut()")
    public void afterThrow(JoinPoint joinPoint) {
        Connection conn = DataSourcePool.getConnection();
        if (conn != null ) {
            try {
                //事务回滚
                conn.rollback();
                //更新事务结束标识
                DBUtil.setTranscationalOver();
                System.out.println("事务回滚");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                //释放资源（主要针对数据库连接）
               DataSourcePool.returnConnection();
            }
        }
    }


}
